package com.simon.nearbyfootball.baidu.adapter;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.simon.nearbyfootball.app.R;

public class BaiduMapViewAdapter implements BDLocationListener{
	private static BaiduMapViewAdapter INSTANCE = null;
	private BaiduLocationAdapter mBaiduLocationAdapter;
	
	MapView mMapView;
	BaiduMap mBaiduMap;
	boolean isFirstLoc = true;
	
	
	public static BaiduMapViewAdapter getInstance(MapView mapView){
		if(INSTANCE == null){
			INSTANCE = new BaiduMapViewAdapter();
		}
		INSTANCE.init(mapView);
		return INSTANCE;
	}
	
	private void init(MapView mapView){
		mBaiduLocationAdapter = BaiduLocationAdapter.getInstance();
		mMapView = mapView;
		mBaiduMap = mMapView.getMap();
		mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduLocationAdapter.setLocationListener(this);
		if(!mBaiduLocationAdapter.isStarted()){
			mBaiduLocationAdapter.start();
		}
	}
	
	
	public void start(){
		
	}
	
	
	public void stop(){
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		
		// clear location listener
		mBaiduLocationAdapter.setLocationListener(null);
	}
	
	public void onPause(){
		if(mMapView == null){
			return;
		}
		mMapView.onPause();
	}
	
	
	public void onResume(){
		if(mMapView == null){
			return;
		}
		mMapView.onResume();
	}

	@Override
	public void onReceiveLocation(BDLocation location) {
		// TODO Auto-generated method stub
		if (location == null || mMapView == null)
			return;
		MyLocationData locData = new MyLocationData.Builder()
				.accuracy(location.getRadius())
				.direction(100).latitude(location.getLatitude())
				.longitude(location.getLongitude()).build();
		mBaiduMap.setMyLocationData(locData);
		if (isFirstLoc) {
			isFirstLoc = false;
			LatLng ll = new LatLng(location.getLatitude(),
					location.getLongitude());
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			mBaiduMap.animateMapStatus(u);
		}
	}
	
	public void addOverlay(double latitude,double longitude){
		LatLng point = new LatLng(latitude, longitude);  
		BitmapDescriptor bitmap = BitmapDescriptorFactory  
		    .fromResource(R.drawable.icon_gcoding);
		OverlayOptions option = new MarkerOptions()  
		    .position(point)
		    .icon(bitmap);
		mBaiduMap.addOverlay(option);
	}
	
	public BaiduMap getBaiduMapObject(){
		return mBaiduMap;
	}
	
}
